// pages/index/index.js
Page({
  data: {
    comments: []
  },
  
  onLoad() {
    this.getComments();
  },
  
  onShow() {
    this.getComments();
  },
  
  async getComments() {
    wx.showLoading({
      title: '加载中...'
    });
    
    try {
      const db = wx.cloud.database();
      const res = await db.collection('topics')
        .orderBy('createTime', 'desc')
        .get();
      
      // 从缓存获取用户点赞状态
      const likeStatus = wx.getStorageSync('likeStatus') || {};
      const dislikeStatus = wx.getStorageSync('dislikeStatus') || {};
      
      // 格式化时间并处理内容
      const comments = res.data.map(item => {
        return {
          ...item,
          createTime: this.formatTime(item.createTime),
          images: item.images || [],
          liked: likeStatus[item._id] || false,
          disliked: dislikeStatus[item._id] || false,
          likeCount: item.likeCount || 0,
          dislikeCount: item.dislikeCount || 0
        }
      });
      
      this.setData({
        comments: comments
      });
    } catch (err) {
      console.error('获取评论失败:', err);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  
  // 格式化时间
  formatTime(date) {
    const now = new Date();
    const target = new Date(date);
    const diff = now - target;
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
      return Math.floor(diff / day) + '天前';
    } else {
      return target.getFullYear() + '-' + 
             (target.getMonth() + 1).toString().padStart(2, '0') + '-' + 
             target.getDate().toString().padStart(2, '0');
    }
  },
  
  // 点赞处理
  handleLike(e) {
    const topicId = e.currentTarget.dataset.id;
    const comments = this.data.comments.map(item => {
      if (item._id === topicId) {
        const isLiked = !item.liked;
        return {
          ...item,
          liked: isLiked,
          likeCount: isLiked ? (item.likeCount || 0) + 1 : Math.max(0, (item.likeCount || 0) - 1),
          disliked: isLiked ? false : item.disliked,
          dislikeCount: isLiked ? Math.max(0, (item.dislikeCount || 0) - 1) : item.dislikeCount
        };
      }
      return item;
    });
    
    this.setData({ comments });
    
    // 更新本地缓存
    const likeStatus = wx.getStorageSync('likeStatus') || {};
    likeStatus[topicId] = !likeStatus[topicId];
    wx.setStorageSync('likeStatus', likeStatus);
    
    if (comments.find(item => item._id === topicId).disliked) {
      const dislikeStatus = wx.getStorageSync('dislikeStatus') || {};
      dislikeStatus[topicId] = false;
      wx.setStorageSync('dislikeStatus', dislikeStatus);
    }
    
    // 更新数据库
    this.updateTopicInDB(topicId, {
      likeCount: comments.find(item => item._id === topicId).likeCount,
      dislikeCount: comments.find(item => item._id === topicId).dislikeCount
    });
  },
  
  // 点踩处理
  handleDislike(e) {
    const topicId = e.currentTarget.dataset.id;
    const comments = this.data.comments.map(item => {
      if (item._id === topicId) {
        const isDisliked = !item.disliked;
        return {
          ...item,
          disliked: isDisliked,
          dislikeCount: isDisliked ? (item.dislikeCount || 0) + 1 : Math.max(0, (item.dislikeCount || 0) - 1),
          liked: isDisliked ? false : item.liked,
          likeCount: isDisliked ? Math.max(0, (item.likeCount || 0) - 1) : item.likeCount
        };
      }
      return item;
    });
    
    this.setData({ comments });
    
    // 更新本地缓存
    const dislikeStatus = wx.getStorageSync('dislikeStatus') || {};
    dislikeStatus[topicId] = !dislikeStatus[topicId];
    wx.setStorageSync('dislikeStatus', dislikeStatus);
    
    if (comments.find(item => item._id === topicId).liked) {
      const likeStatus = wx.getStorageSync('likeStatus') || {};
      likeStatus[topicId] = false;
      wx.setStorageSync('likeStatus', likeStatus);
    }
    
    // 更新数据库
    this.updateTopicInDB(topicId, {
      likeCount: comments.find(item => item._id === topicId).likeCount,
      dislikeCount: comments.find(item => item._id === topicId).dislikeCount
    });
  },
  
  // 更新数据库中的话题数据
  async updateTopicInDB(topicId, data) {
    try {
      const db = wx.cloud.database();
      await db.collection('topics').doc(topicId).update({
        data: data
      });
    } catch (err) {
      console.error('更新话题数据失败:', err);
    }
  },
  
  goToWritePage() {
    wx.navigateTo({
      url: '/pages/write/write'
    });
  }
});